package com.eol.common.jwt;

import com.eol.common.base.BaseResponseCode;
import com.eol.common.config.SystemPropertiesConfig;
import com.eol.common.exception.BaseException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * Created with IntelliJ IDEA.
 * User: liulinhui
 * Date: 2018-11-26
 * Time: 19:41
 * Description:  JwtUtils
 */
@Component
public class JwtUtils {
    @Resource
    private PrivateKey privateKey;

    @Resource
    private PublicKey publicKey;

    @Resource
    private SystemPropertiesConfig systemPropertiesConfig;

    /**
     * 生成token
     *
     * @param tokenData token data对象
     * @return String
     */
    public String generateToken(TokenData tokenData) {
        return JWTHelper.generateToken(tokenData, privateKey);
    }

    /**
     * 解析token
     *
     * @param token token
     * @return TokenData
     */
    public TokenData parseToken(String token) {
        TokenData tokenData = JWTHelper.getInfoFromToken(token, publicKey);
        long slot = System.currentTimeMillis() - tokenData.getT();
        if (slot > systemPropertiesConfig.getJwt().getExpiration())
            throw new BaseException(BaseResponseCode.TOKEN_EXPIRED);
        return JWTHelper.getInfoFromToken(token, publicKey);
    }


    /**
     * 计算token剩余时间
     *
     * @param tokenData tokenData
     * @return 剩余时间
     */
    public long getTokenLeftTime(TokenData tokenData) {
        long slot = System.currentTimeMillis() - tokenData.getT();
        return systemPropertiesConfig.getJwt().getExpiration() - slot;
    }
}
